<template>
  <div class="currency-box">
    <div class="left">
      <!-- 工单列表的搜索 Start -->
      <header>
        <div class="search">
          <a-input
            placeholder="输入设备名称"
            v-model="searchInfo.keyWords"
            @keyup.enter="upList"
          />
        </div>
        <div class="icon">
          <a-popover
            placement="bottom"
            trigger="click"
            v-model="visible"
            title="筛选"
          >
            <template slot="content">
              <a-form-model :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-model-item label="填写时间">
                  <a-range-picker
                    @change="onTimeChange"
                    :defaultValue="defaultdateList"
                  />
                </a-form-model-item>
                <a-form-model-item label="厂区">
                  <a-select
                    :allowClear="true"
                    mode="multiple"
                    :maxTagCount="1"
                    class="selectwidth"
                    v-model="searchInfo.WSType"
                    placeholder="请选择"
                    @change="handleChange"
                  >
                    <a-select-option
                      v-for="item in WSTypeList"
                      :key="item.type"
                      :value="item.type"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="车间">
                  <a-select
                    :allowClear="true"
                    mode="multiple"
                    class="selectwidth"
                    v-model="searchInfo.SegmentIDs"
                    placeholder="请选择"
                  >
                    <a-select-option
                      v-for="item in QSegmentList"
                      :key="item.type"
                      :value="item.type"
                      >{{ item.name }}</a-select-option
                    >
                  </a-select>
                </a-form-model-item>
                <a-form-model-item label="资产编码">
                  <a-input v-model="searchInfo.ProSegmentAssetNo" />
                </a-form-model-item>
                <a-form-model-item label="设备编码">
                  <a-input v-model="searchInfo.ProSegmentNo" />
                </a-form-model-item>
                <a-form-model-item label="设备名称">
                  <a-input v-model="searchInfo.ProSegmentName" />
                </a-form-model-item>
                <a-form-model-item label="状态">
                  <a-select
                    style="width: 100%"
                    v-model="searchInfo.JobRecordStatusList"
                    mode="multiple"
                    :maxTagCount="1"
                  >
                    <a-select-option
                      :value="item.num"
                      v-for="item in jobRecordStatusList"
                      :key="item.num"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>

                <a-form-model-item
                  style="display: flex; justify-content: flex-end"
                >
                  <a-button class="default-button" @click="upList">
                    查询
                  </a-button>
                </a-form-model-item>
              </a-form-model>

              <!-- <div style="display: flex; justify-content: flex-end;">
                                  
                              </div> -->
            </template>
            <a-icon type="filter" class="icon-class" />
          </a-popover>
        </div>
      </header>
      <!-- 工单列表的搜索 End -->
      <!-- 工单列表的展示 Start -->
      <section
        infinite-scroll-immediate-check="false"
        infinite-scroll-listen-for-event="false"
        v-infinite-scroll="handleinfiniteOnLoad"
        infinite-scroll-disabled="busy"
        infinite-scroll-distance="20"
      >
        <div
          :class="[
            'section-box',
            index == currentIndex ? 'section-active' : '',
          ]"
          v-for="(item, index) in list"
          :key="index"
          @click="checkPacking(item, index)"
        >
          <div class="section-box-info">
            <p class="dimension-text">
              设备编码:{{ item.ProSegmentNo || "/" }}
            </p>
            <p class="dimension-text">
              资产编号:{{ item.ProSegmentAssetNo || "/" }}
            </p>
            <p class="dimension-text">
              设备名称:{{ item.ProSegmentName || "/" }}
            </p>

            <p>工作集编码:{{ item.JobGroupNo || "/" }}</p>
            <p>工作集名称:{{ item.JobGroupName || "/" }}</p>
          </div>
        </div>
      </section>
      <!-- 工单列表的展示 End -->
    </div>
    <a-spin
      :spinning="loading"
      tip="加载中..."
      size="large"
      class="right batch-printing-right"
    >
      <div class="spin-box-div">
        <!-- 选择该工单的批记录 Start -->
        <header>
          <div
            class="type-list-box"
            style="height: 100%"
            v-show="batchList.length == 0"
          >
            <div class="info-box">
              <span>暂无绑定项</span>
            </div>
          </div>

          <div
            v-for="(itm, idx) in batchList"
            :key="idx"
            :class="['type-list-box', idx == mateIdx ? 'active' : '']"
          >
            <div class="batch-check-box">
              <a-checkbox @change="onChange(itm)"> </a-checkbox>
            </div>

            <article class="article-list-box">
              <div class="article-top" @click="checkBatch(itm, idx)">
                <div class="info-box">
                  <span>资产编码:</span><span>{{ itm.ProSegmentAssetNo }}</span>
                </div>
                <div class="info-box">
                  <span>工作集:</span><span>{{ itm.JobGroupName }}</span>
                </div>
                <div class="info-box">
                  <span>模板:</span><span>{{ itm.JobTempletName }}</span>
                </div>
                <div class="info-box">
                  <span>表单类型:</span
                  ><span>{{
                    itm.TableType == 1
                      ? "单例表单"
                      : itm.TableType == 2
                      ? "聚合表单"
                      : "视图表单"
                  }}</span>
                </div>
                <div class="info-box">
                  <span>填写进度:</span
                  ><span
                    >{{ itm.CompletedJobItemCount }}/{{
                      itm.JobItemTotal
                    }}</span
                  >
                </div>
                <div class="info-box">
                  <span>状态:</span
                  ><span
                    :style="{ color: mateFind(itm.JobRecordStatus).color }"
                    >{{ mateFind(itm.JobRecordStatus).name }}</span
                  >
                </div>
              </div>
              <div class="info-box">
                <span>操作:</span>
                <span>
                  <general-button
                    class="default-button"
                    style="margin-right: 5px"
                    size="small"
                    @operation="onEdit(itm)"
                    :btnDisabled="idx != mateIdx"
                    btnText="修改"
                    btnPowerNum="36C7BF94-1FF2-4E5F-8D47-AD2AE4B743A3"
                  >
                  </general-button>
                  <!-- <a-button type="primary" size="small" @click="onPrint" :disabled="idx != mateIdx">
                    打印
                  </a-button> -->
                </span>
              </div>
            </article>
          </div>
        </header>
        <!-- 选择该工单的批记录 End -->
        <section style="padding: 10px 0">
          <!-- 需要打印且展示的部分 Start -->
          <batch-box
            v-if="mateCurrentInfo.TableType == 1"
            ref="print"
            id="printTable"
            :list="batchDetailList"
            :item="mateCurrentInfo"
          ></batch-box>
          <!-- 需要打印且展示的部分 End  -->

          <!-- 聚合表单 Start -->
          <polymerize-box
            v-if="
              mateCurrentInfo.TableType == 2 || mateCurrentInfo.TableType == 3
            "
            :isShowBody="true"
            ref="print"
            :list="batchDetailList"
            :item="mateCurrentInfo"
            :headerList="polyHeaderList"
          ></polymerize-box>
          <!-- 聚合表单 End -->
        </section>
      </div>
    </a-spin>

    <!-- 修改工作集信息 Start -->
    <edit-batch
      :show.sync="editPrint"
      :mitem="mateCurrentInfo"
      :list="polyList"
      @upList="upListFun"
    ></edit-batch>
    <!-- 修改工作集信息 End -->
  </div>
</template>

<script>
import {
  getPackingPlanList,
  getJobRecordToList,
  getJobRecordDetailList,
  getJobRecordDetailGroupList,
  getJobRecordList,
} from "@/api/JobRecord";
import {
  getJobGroupListByProSegment,
  getJobRecordListByProSegment,
} from "@/api/view-disinfection-jobRecord";
import { GetWorkShopTypesAll } from "@/api/WorkShopType/index";
import { GetSegments } from "@/api/NBCSegment/index";
import moment from "moment";
import BatchBox from "./children/batch-table-box.vue";
import PolymerizeBox from "./children/polymerize-table-box.vue";
import PrintDrawer from "./children/print-drawer.vue";
import EditBatch from "./children/edit-batch.vue";
import polymerizeTitle from "@/common/handle-title";
import GeneralButton from "@/components/be-current-btn.vue";
import { debounce } from "@/common/debounce";
export default {
  name: "ViewDisinfectionJobRecord",
  components: {
    BatchBox,
    PolymerizeBox,
    PrintDrawer,
    EditBatch,
    GeneralButton,
  },
  data() {
    return {
      loading: false, //加载完成
      currentIndex: 0, //当前选中
      WSTypeList: [], //厂区列表
      QSegmentList: [], //车间列表
      jobRecordStatusList: [
        { name: "已创建未填写", num: 10 },
        { name: "填写中", num: 11 },
        { name: "已填写未审核", num: 12 },
        { name: "已审核", num: 13 },
      ], //状态列表
      jobRecordStatusData: [12], //当前状态
      defaultdateList: [],
      visible: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      busy: true, //列表滚动
      searchInfo: {
        keyWords: "",
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        JobRecordStatusList: [12], //状态
        startDt: "", //开始时间
        endDt: "", //结束时间
        WSType: [], //厂区
        SegmentID: "", //车间
        SegmentIDs: [], //车间
        ProSegmentAssetNo: "", //资产编码
        ProSegmentNo: "", //设备编码
        ProSegmentName: "", //设备名称
      }, //工单列表搜索参数
      list: [], //工单列表
      listNum: 0, //总条数
      listInfo: {}, //选中的列表信息
      mateInfo: [
        { name: "已创建", type: 10, color: "#1487fa" },
        { name: "填写中", type: 11, color: "#e4a15e" },
        { name: "填报完成", type: 12, color: "#84c25b" },
        { name: "已审核", type: 13, color: "#e4a15e" },
        { name: "打回", type: 14, color: "#fe6253" },
        { name: "禁用", type: 2, color: "#fe6253" },
        { name: "删除", type: 3, color: "#fe6253" },
      ], //状态筛选
      mateInfos: [
        { name: "灌装", type: 10 },
        { name: "包装", type: 11 },
        { name: "折叠", type: 12 },
      ], //状态筛选
      mateIdx: 0, //工作集选中项
      mateCurrentInfo: {}, //选中的工作集
      batchList: [], //工作集列表
      batchDetailList: [], //工作记录明细列表
      polyHeaderList: [], //聚合表单表头

      allPrintList: [], //批量打印列表

      editPrint: false, //修改填写项信息
      polyInfo: {}, //默认添加项
      polyList: [], //修改列表
    };
  },
  watch: {
    visible: {
      handler(newVal, oldValue) {
        if (newVal) {
          this.searchInfo.keyWords = "";
        }
      },
      deep: true,
    },
  },
  methods: {
    //获取厂区列表
    async GetWorkShopTypesAllFun() {
      let that = this;
      let res = await GetWorkShopTypesAll(10);
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.WSType, name: item.WSName });
        });
        that.WSTypeList = wtList;
      } else {
        that.$message.error(res.Message);
      }
    },
    //选中厂区
    handleChange(value) {
      let that = this;
      if (value) {
        that.GetSegmentsAllFun(that.searchInfo.WSType, true);
      }
    },
    //获取车间列表
    GetSegmentsAllFun: debounce(async function (WSType, ispplist = false) {
      let that = this;
      let SegSegmentID = [
        "1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3",
        "5D494A1E-5F24-4036-9350-2E442A19FE87",
        "CCDB0114-7026-4218-A507-5C00E870B0B3",
        "12FF8C8D-B2DC-4554-AA9B-91703F4AB200",
      ];
      //新建单据的时候，判断类型。只显示对应类型车间
      if (!ispplist && JSON.stringify(that.selectedPPList) !== "{}") {
        switch (that.selectedPPList.OrderType) {
          case 10: //灌包
            SegSegmentID = ["5D494A1E-5F24-4036-9350-2E442A19FE87"];
            break;
          case 11: //包装
            SegSegmentID = ["1735FA0C-33E4-4B25-AAA2-DE084FB7D1E3"];
            break;
          case 12: //折叠
            SegSegmentID = ["CCDB0114-7026-4218-A507-5C00E870B0B3"];
            break;
          case 13: //冲裁
          case 14: //无纺布
          case 15: //挑选
            SegSegmentID = ["12FF8C8D-B2DC-4554-AA9B-91703F4AB200"];
            break;
          default:
            break;
        }
      }
      let res = await GetSegments({
        SegSegmentID: SegSegmentID,
        WSTypeList: WSType,
      });
      if (res.Status == 10000) {
        let wtList = [];
        res.Data.map((item) => {
          wtList.push({ type: item.SegmentID, name: item.SegmentName });
        });
        if (ispplist) {
          that.QSegmentList = wtList;
        } else {
          that.PPQSegmentList = wtList;
        }
      } else {
        that.$message.error(res.Message);
      }
    }),

    //滚动方法
    handleinfiniteOnLoad() {
      this.busy = true;
      setTimeout(() => {
        this.searchInfo.pageRequestModel.pageIndex += 1;
        this.getJobGroupListByProSegmentFun();
      }, 1000);
    },
    /* 打印页面 */
    onPrint() {
      this.$store.commit("upPrintShow", true);
      this.$print(this.$refs.print);
    },
    /* 修改打印信息 */
    async onEdit(item) {
      let res = await getJobRecordDetailList(item.JobRecordID);

      /* 先筛选出为10的是不需要填写的信息 */
      let list = res.Data.filter((item) => item.DataTypeIndex != 10);
      /* 将筛选后的列表进行排序  */
      list.sort((a, b) => {
        return a.JobRecordDetailIndex - b.JobRecordDetailIndex;
      });
      /* 找出排序最大值 */
      let batchDetailNum = list[list.length - 1].JobRecordDetailIndex;
      /* 创建空数组 */
      let detailList = [];

      /* 通过遍历获取最大值添加列表中相对应的JobRecordDetailIndex项为一行 push进detailList数组 */
      for (let index = 1; index <= batchDetailNum; index++) {
        let newlist = list.filter((fitm) => fitm.JobRecordDetailIndex == index);
        detailList.push(newlist);
      }

      /* 存储第一项为添加项 */
      this.polyInfo = JSON.parse(JSON.stringify(detailList[0]));

      /* 再次排序 */
      detailList.map((itm) => {
        itm.sort((a, b) => {
          return a.JobItemIndex - b.JobItemIndex;
        });
      });

      this.polyList = detailList;

      this.editPrint = true;
    },
    /* 查询列表 */
    upList() {
      this.searchInfo.pageRequestModel.pageIndex = 1;
      this.list = [];
      let { keyWords, batchNo, packingPlanNo } = this.searchInfo;
      if (keyWords != "") {
        this.searchInfo = {
          ...this.searchInfo,
          ProSegmentName: keyWords,
        };
      }
      this.getJobGroupListByProSegmentFun();
      this.visible = false;
    },
    /* 批记录状态筛选 */
    mateFind(type) {
      return this.mateInfo.find((item) => item.type == type);
    },
    /* 工单状态筛选 */
    mateFinds(type) {
      return this.mateInfos.find((item) => item.type == type);
    },
    /* 切换选中工作集 */

    /* 修改后更新表格 */
    async upListFun() {
      this.loading = true;
      if (this.mateCurrentInfo.TableType == 1) {
        this.getJobRecordDetailGroupListFun(this.mateCurrentInfo.JobRecordID);
      } else {
        this.getJobRecordDetailListFun(this.mateCurrentInfo.JobRecordID);
      }
    },
    /* 赋值工作集后查询该工作集下的批记录填写信息,批记录用 JobItemIndex字段排序 JobGroup为批记录名称 （建议填写用。隔开 暂时用。分割 */
    async checkBatch(itm, idx) {
      this.loading = true;

      this.mateIdx = idx;
      this.mateCurrentInfo = itm;
      if (this.mateCurrentInfo.TableType == 1) {
        this.getJobRecordDetailGroupListFun(itm.JobRecordID);
      } else {
        this.getJobRecordDetailListFun(itm.JobRecordID);
      }
    },
    /* 切换选中工单 */
    checkPacking(item, index) {
      this.currentIndex = index;
      this.listInfo = item;
      this.mateIdx = 0;
      this.getJobRecordToListFun();
    },
    //筛选七天时间
    onTimeChange(date, dateString) {
      this.searchInfo = {
        ...this.searchInfo,
        startDt: dateString[0],
        endDt: dateString[1],
      };
    },
    /* 查询工单列表  参数keyWords工单号查询   查询到有值再进行查询该工单的工作集 */
    async getJobGroupListByProSegmentFun() {
      let res = await getJobGroupListByProSegment(this.searchInfo);
      this.list = this.list.concat(res.Data.Data);
      this.listNum = res.Data.TotalNumber;
      if (this.list[0]) {
        this.listInfo = this.list[0];
        this.currentIndex = 0;
        this.getJobRecordToListFun();
      } else {
        this.listInfo = {};
        this.currentIndex = 0;
        this.batchList = [];
      }

      if (res.Data.Data.length == 0) {
        this.busy = true;
      } else {
        this.busy = false;
      }
    },

    /* 查询工单的批记录,传入参数选中工单的工单id 如该工单有批记录再操作查询项并通过  JobItemIndex排序*/
    async getJobRecordToListFun() {
      let { ProSegmentID, CreateDt } = this.listInfo;
      let res = await getJobRecordListByProSegment({
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        ProSegmentID,
        CreateDt,
      });

      this.batchList = res.Data.Data.map((item) => {
        item.checkStatus = false;
        return item;
      });

      if (this.batchList[0]) {
        this.loading = true;
        this.mateCurrentInfo = this.batchList[0];
        let { JobRecordID } = this.batchList[0];
        if (this.mateCurrentInfo.TableType == 1) {
          this.getJobRecordDetailGroupListFun(JobRecordID);
        } else {
          this.getJobRecordDetailListFun(JobRecordID);
        }
      } else {
        this.loading = false;
        this.mateCurrentInfo = {};
        this.polyHeaderList = [];
        this.batchDetailList = [];
      }
    },
    /* 多选选中项 */
    onChange(e) {
      e.checkStatus = !e.checkStatus;
    },

    /* 查询工作集对应的批记录项  传入工作集id JobRecordID 用于单例列表*/
    async getJobRecordDetailGroupListFun(JobRecordID) {
      let res = await getJobRecordDetailGroupList(JobRecordID);
      this.batchDetailList = res.Data.sort((a, b) => {
        return a.JobItemIndex - b.JobItemIndex;
      });
      this.batchDetailList.map((item) => {
        item.JobGroup = item.JobGroup.split("。");
        item.JobRecordDetailList = item.JobRecordDetailList.sort((a, b) => {
          return a.JobItemIndex - b.JobItemIndex;
        });
      });
      this.loading = false;
    },
    /* 查询工作集对应的批记录项  传入工作集id JobRecordID 用于聚合列表*/
    async getJobRecordDetailListFun(JobRecordID) {
      let res = await getJobRecordDetailList(JobRecordID);
      let stagingHeader = res.Data.filter(
        (item) => item.JobRecordDetailIndex == 1
      );

      stagingHeader = stagingHeader.sort((a, b) => {
        return a.JobItemIndex - b.JobItemIndex;
      });
      this.polyHeaderList = polymerizeTitle.handleTitleList(stagingHeader);
      /* 先根据 JobRecordDetailIndex 把每一项排序 */
      let stagingBatchDetailList = res.Data.sort((a, b) => {
        return a.JobRecordDetailIndex - b.JobRecordDetailIndex;
      });
      /* 通过 pop方法获取数组最后一位确定共几行 */
      let batchDetailNum =
        stagingBatchDetailList[stagingBatchDetailList.length - 1]
          .JobRecordDetailIndex;
      /* 定义一个空数组 */
      let detailList = [];

      /* 通过遍历获取最大值添加列表中相对应的JobRecordDetailIndex项为一行 push进detailList数组 */
      for (let index = 1; index <= batchDetailNum; index++) {
        let list = stagingBatchDetailList.filter(
          (fitm) => fitm.JobRecordDetailIndex == index
        );
        detailList.push(list);
      }

      /* 遍历结束后将子项排序后赋值 */
      this.batchDetailList = detailList.map((ditm) => {
        ditm.sort((a, b) => {
          return a.JobItemIndex - b.JobItemIndex;
        });
        ditm = polymerizeTitle.handleTitleList(ditm);
        return ditm;
      });

      this.loading = false;
    },
  },
  mounted() {
    this.defaultdateList = [
      moment().subtract(6, "days").format("YYYY-MM-DD"),
      moment().format("YYYY-MM-DD"),
    ];
    this.searchInfo = {
      ...this.searchInfo,
      startDt: this.defaultdateList[0],
      endDt: this.defaultdateList[1],
    };
    this.getJobGroupListByProSegmentFun();
    this.GetWorkShopTypesAllFun();
  },
};
</script>

<style lang="less" scoped>
.ant-spin-spinning {
  position: absolute;
  top: calc(50% - 100px);
  left: 50%;
  z-index: 999999999999999999999;
  color: blue;
}

/deep/.ant-spin-nested-loading {
  height: 100%;
}

/deep/.ant-spin-container {
  height: 100%;
}

.spin-box-div {
  height: 100%;
  display: flex;
  flex-direction: column;
}

//旋转图标颜色
.ant-spin-lg .ant-spin-dot i {
  // background: #fff;
  background: blue;
}

.ant-spin-text {
  color: blue;
}

.currency-box {
  position: relative;

  .section-box-info {
    p {
      margin: 0;
    }
  }
}

.article-list-box {
  flex: 1;
  display: flex;
  flex-direction: column;

  .article-top {
    flex: 1;
  }
}

.batch-printing-right {
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  width: 0;

  header {
    display: flex;
    overflow-x: auto;
    padding-bottom: 0.3125rem;
    border-bottom: 2px solid #f0f2f5;

    .type-list-box {
      display: flex;
      flex-direction: column;
      position: relative;
      cursor: pointer;
      flex: 0 0 25%;
      background: #f0ebeb;
      padding: 0.3125rem;
      border-radius: 0.3125rem;
      margin-right: 0.3125rem;

      .info-box {
        display: flex;

        span:nth-child(1) {
          flex: 1;
        }

        span:nth-child(2) {
          flex: 3;
        }
      }
    }

    .defalue-box {
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      cursor: pointer;
      height: 100%;
      flex: 0 0 5%;
      background: #1890ff;
      padding: 0.3125rem;
      border-radius: 0.3125rem;
      margin-right: 0.3125rem;

      span {
        display: flex;
        color: #ffffff;
        writing-mode: vertical-lr;
      }
    }
  }

  section {
    flex: 1;
    overflow: auto;
  }
}

.batch-check-box {
  display: flex;
  justify-content: flex-end;
}

.active {
  background-color: #dcf0ef !important;
}
</style>
